package com.gaofans.vertx.boot.common.verticle;

import com.google.common.collect.Lists;
import io.vertx.core.AsyncResult;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;

public class AnnotationVerticleDiscoverer implements ApplicationContextAware,VerticleDiscoverer {

    private ApplicationContext applicationContext;

    private static final Logger LOG = LoggerFactory.getLogger(AnnotationVerticleDiscoverer.class);

    @Override
    public Collection<VerticleDefinition> findVerticles() {
        String[] beanNames = this.applicationContext.getBeanNamesForAnnotation(Verticle.class);
        ArrayList<VerticleDefinition> verticleDefinitions = Lists.newArrayListWithCapacity(beanNames.length);
        for (String beanName : beanNames) {
            io.vertx.core.Verticle verticle = this.applicationContext.getBean(beanName, io.vertx.core.Verticle.class);
            VerticleDefinition verticleDefinition = new VerticleDefinition();
            verticleDefinition.setVerticle(verticle);
            Verticle annotation = this.applicationContext.findAnnotationOnBean(beanName, Verticle.class);
            assert annotation != null;
            ResultHandlerBuilder handlerBuilder = this.applicationContext.getBean(annotation.handler());
            Handler<AsyncResult<String>> handler = handlerBuilder.build();
            DeploymentOptionsBuilder optionsBuilder = this.applicationContext.getBean(annotation.options());
            DeploymentOptions options = optionsBuilder.build();
            verticleDefinition.setHandler(handler);
            verticleDefinition.setDeploymentOptions(options);
            verticleDefinitions.add(verticleDefinition);
            verticleDefinition.setName(beanName);
            LOG.info("找到verticle: name[{}],handler[{}],options[{}]",verticleDefinition.getName(),verticleDefinition.getHandler(),verticleDefinition.getDeploymentOptions());
        }
        if(verticleDefinitions.size() == 0){
            LOG.info("未找到verticle");
        }
        return verticleDefinitions;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
